//
//  OAuthTools.swift
//  Webo10
//
//  Created by ChengXiwu on 2017/7/29.
//  Copyright © 2017年 ChengXiwu. All rights reserved.
//

import UIKit

class OAuthTools{
    
    // 单例
    static let oauth = OAuthTools()
    
    // token字典
    private var tokenDict: [String: Any]?{
        if let token = UserAccountViewModel.userAccount.accessToken {
            return ["access_token": token]
        }
        return nil
    }
    
    // 用户账户网络方法
    // MARK: - 应用程序信息
    fileprivate let appKey = "806301040"
    fileprivate let appSecret = "06128c86282a46942852e1d130860535"
    fileprivate let redirectUri = "http://www.baidu.com"
    
    /// 授权访问URL - https://api.weibo.com/oauth2/authorize?client_id=806301040&redirect_uri=http://www.baidu.com
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl: URL {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        return URL(string: url)!
    }
    
    // 加载AccessToken,并保存
    func loadAccessToken(code: String, finished: @escaping AsyncCallback) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id": appKey,
                          "client_secret": appSecret,
                          "grant_type": "authorization_code",
                          "code": code,
                          "redirect_uri": redirectUri]
        
        NetworkTools.networkTools.sendRequest(method: .POST, url: url, parameters: parameters) { (res, error) in
            // 判断错误
            if error != nil {
                finished(false, "您的网络不给力,请稍后再试")
                return
            }
            
            logPrint(res)
            UserAccountViewModel.userAccount.account = UserAccount(dict: res as! [String: Any])
            self.loadUserInfo(account: UserAccountViewModel.userAccount.account!, finished: finished)
        }
        
    }
    
    /// 加载用户信息
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(account: UserAccount, finished: @escaping AsyncCallback) {
        
        guard var parameters = tokenDict else {
            finished(false, "token过期了")
            return
        }

        let url = "https://api.weibo.com/2/users/show.json"
        
        parameters["uid"] = UserAccountViewModel.userAccount.account!.uid!
        
        NetworkTools.networkTools.sendRequest(method: HttpMethod.GET, url: url, parameters: parameters){ (res, error) in
            
            if error != nil {
                finished(false, "加载用户出错了")
                return
            }
            
            guard let dict = res as? [String: Any] else {
                finished(false, "反序列化结果格式错误")
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            account.saveUserAccount()
            finished(true, nil)
        }
        
    }
    
    /// 加载微博数据
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(finished: @escaping AsyncCallbackWithData){
        
        guard let parameters = tokenDict else {
            finished(false, nil, "token过期了")
            return
        }

        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        NetworkTools.networkTools.sendRequest(method: HttpMethod.GET, url: url, parameters: parameters){ (res, error) in
            
            if error != nil {
                finished(false, nil, "微博数据获取出错了")
                return
            }
            
            guard let dicts = (res as? [String: Any])?["statuses"] as? [[String: Any]] else {
                finished(false, nil, "反序列化结果格式错误")
                return
            }
            
            var statuses = [Status]()
            
            for dict in dicts{
                statuses.append(Status(dict: dict))
            }
            
            finished(true, statuses, nil)
        }
        
    }
    
}
